class GroupsController < ApplicationController

  def index
    @groups = current_user.groups
  end

  def show
    group = Group.find params[:id]
    @messages = group.messages
  end

  def all_after
    @messages = Message.where("group_id = ? and created_at >= ? ", params[:group_id], params[:time])
    render "show"
  end

  def add_member
    if params[:group_id].eql?("0")
      @group = Group.new
    else
      @group = Group.find params[:group_id]
    end
    @group.name ||= params[:name] unless params[:name].nil?
    @group.users << current_user
    @group.users << User.find_all_by_id(params[:id])
    if @group.name.nil? || @group.name.eql?("")
      @group.name = @group.users.map(&:email).join(", ")
    end
    @group.save
  end

  def members
    group = Group.find params[:group_id]
    @members = group.users
    relations = GroupUser.where("group_id = ? and shared = ?", group, true).map(&:user_id)
    @members.each do |user|
      unless relations.include? user.id
        user.latitude = nil
        user.longitude = nil
      end
    end
  end

  def set_shared
    relation = GroupUser.where("group_id = ? and user_id = ?", params[:group_id], current_user.id).last
    if relation.shared?
      render :json => { :response => 'ok', :updated => false }.to_json, :status => :ok
      return
    end
    relation.shared = true
    if relation.save
      render :json => { :response => 'ok', :updated => true }.to_json, :status => :ok
    end
  end

  def unset_shared
    relation = GroupUser.where("group_id = ? and user_id = ?", params[:group_id], current_user.id).last
    unless relation.shared?
      render :json => { :response => 'ok', :updated => false }.to_json, :status => :ok
      return
    end
    relation.shared = false
    if relation.save
      render :json => { :response => 'ok', :updated => true }.to_json, :status => :ok
    end
  end

end
